from anthropic import Anthropic
client = Anthropic()
# Step 1: Define a tool
tools = [{
"name": "get_weather",
"description": "Get current weather for a city. Use this when user asks about weather.",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g. 'San Francisco'"
}
},
"required": ["city"]
}
}]
# Step 2: Implement the tool function
def get_weather(city: str) -> dict:
"""Actually fetch weather data."""
# In production, call a real weather API
# For demo, return fake data
return {
"city": city,
"temperature": 72,
"condition": "Sunny",
"humidity": 45
}
# Step 3: Create the agent loop
def run_agent(user_message: str):
"""Simple agent that can use one tool."""
messages = [{"role": "user", "content": user_message}]
# Agent loop - continue until agent stops using tools
while True:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=messages
)
# Check if agent wants to use a tool
if response.stop_reason == "tool_use":
# Agent wants to use a tool
tool_use = next(
block for block in response.content
if block.type == "tool_use"
)
# Execute the tool
if tool_use.name == "get_weather":
tool_result = get_weather(**tool_use.input)
# Add tool use and result to conversation
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": str(tool_result)
}]
})
# Loop continues - agent will think again with tool result
else:
# Agent is done - return final response
final_text = next(
block.text for block in response.content
if hasattr(block, "text")
)
return final_text
# Test the agent
print(run_agent("What's the weather in San Francisco?"))
# Agent thinks: "I need weather data"
# Agent acts: Calls get_weather(city="San Francisco")
# Agent responds: "It's currently 72°F and sunny in San Francisco..."